from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Boolean, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import os

# 数据库配置
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./decision_system.db")

# 创建数据库引擎
engine = create_engine(
    DATABASE_URL,
    connect_args={"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
)

# 创建会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基础模型类
Base = declarative_base()

# 数据源模型
class DataSource(Base):
    __tablename__ = "data_sources"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, index=True)
    url = Column(String(500))
    api_key = Column(String(200))
    data_type = Column(String(50))  # weather, covid, flu, etc.
    update_interval = Column(Integer, default=3600)  # 秒
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

# 数据记录模型
class DataRecord(Base):
    __tablename__ = "data_records"
    
    id = Column(Integer, primary_key=True, index=True)
    source_id = Column(Integer)
    data_type = Column(String(50))
    data_json = Column(Text)  # JSON格式的数据
    timestamp = Column(DateTime, default=datetime.utcnow)

# 决策规则模型
class DecisionRule(Base):
    __tablename__ = "decision_rules"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100))
    description = Column(Text)
    prompt_template = Column(Text)  # AI提示词模板
    data_sources = Column(Text)  # JSON格式的数据源列表
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)

# 对话历史模型
class ChatHistory(Base):
    __tablename__ = "chat_history"
    
    id = Column(Integer, primary_key=True, index=True)
    session_id = Column(String(100))
    user_message = Column(Text)
    ai_response = Column(Text)
    decision_rule_id = Column(Integer, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)

# 依赖注入函数
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
